package cn.tedu._07springaop.egaop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Arrays;

@Component//标记为spring容器管理
@Aspect//标记为切面
public class CartAop {
    //定义切点
    @Pointcut("execution(public int  cn.tedu._07springaop.egaop.CartServiceImpl.*(..))")
    public void doTime(){}

//    @Before("doTime()")
//    public void beforeMethod(JoinPoint joinPoint){
//        String name = joinPoint.getSignature().getName();
//        String  args = Arrays.toString(joinPoint.getArgs());
//        System.out.println(name+"前置通知，参数是"+args);
//
//    }
//    //返回通知，在程序不会出现异常时才会执行
//    @AfterReturning("doTime()")
//    public void afterReturningMethod(JoinPoint joinPoint){
//        String name = joinPoint.getSignature().getName();
//        String  args = Arrays.toString(joinPoint.getArgs());
//        System.out.println(name+"返回通知，参数是"+args);
//    }
//    //后置通知，不管怎样，都会执行（哪怕是抛出异常也会执行）
//    @After("doTime()")
//    public void AfterMethod(JoinPoint joinPoint){
//        String name = joinPoint.getSignature().getName();
//        String  args = Arrays.toString(joinPoint.getArgs());
//        System.out.println(name+"后置通知，参数是"+args);
//    }
    //环绕通知，等同于：前置通知+返回通知+后置通知
    //被try｛｝catch｛｝finally｛｝包裹
    @AfterThrowing("doTime()")//异常通知，只有在异常时才执行此语句
    public void AfterThrowingMethod(JoinPoint joinPoint){
        String name = joinPoint.getSignature().getName();
        String  args = Arrays.toString(joinPoint.getArgs());
        System.out.println(name+"后置通知，参数是"+args);
    }
    @Around("doTime()")
    public Object AroundMethod(ProceedingJoinPoint joinPoint){
        String name = joinPoint.getSignature().getName();
        String  args = Arrays.toString(joinPoint.getArgs());
        Object result = null;
        try {
            System.out.println(name+"前置通知，参数是"+args);
            result = joinPoint.proceed();
            System.out.println(name+"返回通知，参数是"+args);
        }catch (Throwable e){
            System.out.println(name+"异常通知，参数是"+args);
        }finally {
            System.out.println(name+"后置通知，参数是"+args);
        }
        return result;
    }
}







